<template>
  <view class="video-list">
    <view class="swiper-box">
      <view class="swiper-item">
        <video-play
          ref="videoPlayer"
          :src="this.baseURL + '/static/video/' + video_data.src"
          :videoId="video_data.id"
          :autoplay="true"
        ></video-play>
      </view>
      <view class="desc-view">
        <video-left :video="video_data"></video-left>
      </view>
      <video-right
        :video="video_data"
        @comment-click="openCommentPopup"
      ></video-right>
    </view>
  </view>
  <!-- 评论弹窗 -->
  <uni-popup ref="commentPopup" type="bottom" :mask-click="false">
    <view class="comment-popup">
      <view class="popup-header">
        <text class="popup-title">评论</text>
        <uni-icons
          type="close"
          size="24"
          color="#999"
          @click="closeCommentPopup"
        ></uni-icons>
      </view>
      <scroll-view
        class="comment-list"
        scroll-y
        :scroll-into-view="lastCommentId"
      >
        <view
          class="comment-item"
          v-for="comment in filteredComments"
          :key="comment.id"
          :id="'comment-' + comment.id"
        >
          <view class="comment-avatar">
            <image
              class="comment-avatar"
              :src="baseURL + comment.comment_user_avatar"
              mode="aspectFill"
            ></image>
          </view>
          <view class="comment-content">
            <view class="comment-user">{{ comment.comment_username }}</view>
            <view class="comment-text">
              {{ comment.comment_content }}
              <!-- {{ fillData }} -->
            </view>
          </view>
          <view class="comment-icon" style="">
            <i
              class="iconfont icon-like comment-icon-item"
              style="color: #999; font-size: 24px"
              :style="{ color: comment.is_like ? '#ff4949' : '#999' }"
              @click="click_like(comment)"
            ></i>
            <view class="comment-time" style="padding-top: 10px">{{
              comment.comment_date
            }}</view>
          </view>
        </view>
      </scroll-view>
      <view class="comment-input-area">
        <input
          class="comment-input"
          v-model="newComment"
          placeholder="说点什么..."
          @confirm="submitComment"
        />
        <button
          class="comment-submit"
          @click="submitComment"
          :disabled="!newComment.trim()"
        >
          发送
        </button>
      </view>
    </view>
  </uni-popup>
</template>

<script>
  import storage from "@/utils/storage";
  import videoPlay from "@/components/index/video-play.vue";
  import videoLeft from "@/components/index/video-left.vue";
  import videoRight from "@/components/index/video-right.vue";
  import api from "@/API/index.js";

  export default {
    name: "followplayer",
    components: {
      videoPlay,
      videoLeft,
      videoRight,
    },
    props: {
      video_data: {
        type: Object,
        required: true,
        default: () => ({
          src: "",
          id: "",
          title: "",
          desc: "",
          author: "",
          cover: "",
          duration: "",
          playCount: "",
          likeCount: "",
          commentCount: "",
        }),
      },
    },
    data() {
      return {
        current: 0,
        preCurrent: 0,
        video: {},
        currentVideoId: null,
        keyboardHeight: 0,
        newComment: "",
        lastCommentId: "",
        comments: [],
      };
    },
    computed: {
      follow_key() {
        const currentUserId = "1";
        return `${currentUserId}:${this.video.userId}:followed`;
      },
      total() {
        return this.videos.length;
      },
      filteredComments() {
        return this.comments
          .filter((comment) => comment.video_id === this.currentVideoId)
          .map((comment) => ({
            ...comment,
            comment_date: comment.comment_time.slice(0, 10) || "",
          }));
      },
    },
    methods: {
      click_like(comment) {
        // 直接修改当前评论的点赞状态
        comment.is_like = !comment.is_like;

        // 如果需要同步更新原数组（确保响应式）
        const index = this.comments.findIndex((item) => item.id === comment.id);
        if (index !== -1) {
          // 使用 Vue 数组变异方法确保响应式更新
          this.comments.splice(index, 1, { ...comment });
        }
      },
      incrementCommentCount(videoId) {
        const video = this.videos.filter((video) => video.id === videoId);
        if (video.length) {
          video[0].commentCount++;
        }
      },
      submitComment() {
        if (!this.newComment.trim()) return;

        const newCommentObj = {
          id: Date.now(),
          video_id: this.currentVideoId,
          comment_user_avatar: "/static/person/1.jpg", // 默认用户头像
          comment_username: "当前用户",
          comment_content: this.newComment,
          comment_time: format(new Date(), "yyyy-MM-dd HH:mm:ss"),
        };

        this.comments.unshift(newCommentObj);
        this.newComment = "";
        this.lastCommentId = "comment-" + newCommentObj.id;

        // 更新视频评论数
        this.incrementCommentCount(this.currentVideoId);
      },
      openCommentPopup(videoId) {
        this.currentVideoId = videoId;
        this.$refs.commentPopup.open();
        // 暂停当前视频播放
        // 判断 videoPlayer 是否是数组,
        if (Array.isArray(this.$refs.videoPlayer)) {
          this.$refs.videoPlayer[this.current].pause();
        } else {
          this.$refs.videoPlayer.pause();
        }
        this.loadComments();

        // 监听键盘高度变化
        // #ifdef MP-WEIXIN
        uni.onKeyboardHeightChange(this.handleKeyboardHeight);
        // #endif
      },
      closeCommentPopup() {
        this.$refs.commentPopup.close();
        // 恢复视频播放
        if (Array.isArray(this.$refs.videoPlayer)) {
          this.$refs.videoPlayer[this.current].play();
        } else {
          this.$refs.videoPlayer.play();
        }
        // 移除键盘高度监听
        // #ifdef MP-WEIXIN
        uni.offKeyboardHeightChange(this.handleKeyboardHeight);
        // #endif
        this.keyboardHeight = 0;
      },
      async loadComments() {
        const resolveComments = (comments) => {
          const commentsObj = comments.map((comment) => ({
            ...comment,
            is_like: false,
            comment_date: comment.comment_time.slice(0, 10) || "",
          }));
          return commentsObj;
        };
        try {
          api.video
            .getVideoComments()
            .then((res) => {
              this.comments = resolveComments(res.data);
            })
            .catch((err) => {
              if (!err.data && err.statusCode === 500) {
                this.comments = resolveComments(commentsData);
                return;
              }
            });
        } catch (error) {
          console.error("加载评论失败:", error);
          this.comments = resolveComments(commentsData);
        }
      },
    },
    mounted() {
      // 组件挂载后，获取原生DOM并绑定wheel事件
      storage.set(this.follow_key, true);
    },
    beforeDestroy() {
      // 组件销毁前，移除事件监听（避免内存泄漏）
      // #ifdef H5
      // #endif
    },
  };
</script>

<style scoped>
  /* 强制重置所有相关元素高度 */
  .video-list,
  .swiper-box,
  .swiper,
  .swiper-item {
    height: 100%;
  }

  .video-list {
    width: 100vw;
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    padding: 0;
    box-sizing: border-box;
    /* 使用固定计算值确保最小高度 */
    height: calc(100vh - 60px);
  }

  .swiper-box {
    overflow: hidden;
  }

  .swiper-item {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    z-index: 99;
    position: relative;
  }

  .desc-view {
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    z-index: 100;
    padding: 0 15px;
  }

  /* 确保全局样式不影响 */
  .swiper-class,
  .swiper-item {
    display: block;
    height: 100%;
    z-index: 10;
  }
  /* 评论弹窗样式 */
  .comment-popup {
    height: calc(80vh - 50px);
    background-color: #fff;
    border-radius: 16px 16px 0 0;
    display: flex;
    flex-direction: column;
    transition: var(height) 0.3s ease;
    z-index: 1002;
  }

  .popup-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f5f5f5;
  }

  .popup-title {
    font-size: 18px;
    font-weight: bold;
  }

  .comment-list {
    flex: 1;
    padding: 16px 0 16px 16px;
    overflow-y: auto; /* 保留垂直滚动 */
    overflow-x: hidden; /* 禁止水平滚动（避免宽度溢出时显示水平栏） */
    height: calc(80vh - 110px);
    width: 100%; /* 明确宽度为父容器100%，避免被撑开 */
    max-width: 100%; /* 防止宽度超出父容器 */
    box-sizing: border-box; /* 让padding包含在width内，不额外增加宽度 */
  }

  /* 评论项样式 */
  .comment-item {
    display: flex;
    margin-bottom: 16px; /* 与下一条评论的间距 */
    width: 100%;
    justify-content: space-between;
    align-items: flex-start; /* 头像与文字顶部对齐 */
    box-sizing: border-box;
    /* padding: 0 16px; 左右内边距，让评论不贴边 */
    box-sizing: border-box;
  }

  /* 评论输入区域 */
  .comment-input-area {
    display: flex;
    padding: 12px 16px;
    border-top: 1px solid #f5f5f5;
    background-color: #fff;
    margin-bottom: 55px;
  }

  .comment-input {
    flex: 1;
    height: 36px;
    padding: 0 12px;
    border: 1px solid #eee;
    border-radius: 18px;
    margin-right: 12px;
  }

  .comment-submit {
    width: 60px;
    height: 36px;
    line-height: 36px;
    background-color: #ff2442;
    color: white;
    border-radius: 18px;
    font-size: 14px;
  }

  .comment-submit[disabled] {
    opacity: 0.5;
    opacity: 1;
  }

  .comment-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
  }

  .comment-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-self: flex-start;
  }

  .comment-user {
    font-weight: bold;
    margin-bottom: 4px;
    font-size: 12px;
    color: #999;
  }
  .comment-icon {
    width: 60px;
    padding-right: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    height: 100%;
  }
  .comment-text {
    margin-bottom: 4px;
    white-space: normal; /* 保留文本换行 */
    word-wrap: break-word; /* 长单词/链接自动换行 */
    /* text-overflow: ellipsis; */
    width: 100%; /* 改为100%，继承父容器.comment-content的宽度 */
    /* 可选：添加单行/多行省略，避免文本过高导致滚动不明显 */
    /* 多行省略示例（需配合height或line-clamp）：
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    */
  }

  .comment-time {
    font-size: 10px;
    color: #999;
    align-self: flex-end;
  }
  .comment-icon-item {
    align-self: flex-end;
  }
</style>
